package com.sophossystems.client.asmon.dao.spring;

import java.sql.SQLException;
import java.util.List;

import com.sophossystems.client.asmon.dao.SexoDao;
import com.sophossystems.client.asmon.dto.SexoDTO;
import com.sophossystems.client.asmon.exceptions.DaoException;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate3.HibernateCallback;

public class SexoDaoImpl extends AbstractDAO implements SexoDao {
	
	private static Logger logger = Logger.getLogger(SexoDaoImpl.class);

	@Override
	public SexoDTO findByPrimaryKey(final int idSexo) throws DaoException {
		SexoDTO sexo = null;
		try {
			sexo = (SexoDTO) getHibernateTemplate().execute(
					new HibernateCallback() {
						
						@Override
						public Object doInHibernate(Session session) throws HibernateException,
								SQLException {
							final Query oQuery = session.createQuery("SELECT s.idSexo as idSexo, " +
									"s.descripcion as descripcion FROM " 
									+ getTableName() + " s WHERE s.idSexo = :id");
							oQuery.setInteger("id", idSexo);
							SexoDTO sexoDto = (SexoDTO) 
									oQuery.setResultTransformer(
									Transformers.aliasToBean(
											SexoDTO.class)).list().get(0);
							return sexoDto;
							
						}
					});
		} catch (Exception e) {
			logger.error("Error: getSexo, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getPeridoRecoleccion, cause: "
					+ e.getMessage());
		}
		return sexo;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SexoDTO> findAll() throws DaoException {

		List<SexoDTO> sexo = null;
		try {
			sexo = (List<SexoDTO>) getHibernateTemplate().execute(
					new HibernateCallback() {
						
						@Override
						public Object doInHibernate(Session session) throws HibernateException,
								SQLException {
							final Query oQuery = session.createQuery("SELECT s.idSexo as idSexo, " +
									"s.descripcion as descripcion FROM " 
									+ getTableName() + " s ORDER BY s.idSexo");
							List<SexoDTO> sexoDto = oQuery.setResultTransformer(
									Transformers.aliasToBean(SexoDTO.class)).list();
							return sexoDto;
						}
					});
		} catch (Exception e) {
			logger.error("Error: getSexo, cause: " + e.getMessage(), e);
			throw new DaoException("Error: getSexo, cause: "
					+ e.getMessage());
		}
		return sexo;
	}
	
	public String getTableName() {
		return "Sexo";
	}

}
